import axios from 'axios';

// 配置选项
const config = {
  ES_ENDPOINT: process.env.REACT_APP_ES_ENDPOINT || 'http://localhost:9200',
  BUSINESS_INDEX: 'business',
  REVIEW_INDEX: 'reviews'
};

// 默认商家图片
const DEFAULT_BUSINESS_IMAGES = [
  'https://images.unsplash.com/photo-1514933651103-005eec06c04b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80', // 酒吧1
  'https://images.unsplash.com/photo-1572116469696-31de0f17cc34?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80', // 酒吧2
  'https://images.unsplash.com/photo-1470337458703-46ad1756a187?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1169&q=80', // 餐厅1
  'https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', // 餐厅2
  'https://images.unsplash.com/photo-1445116572660-236099ec97a0?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80', // 咖啡厅1
  'https://images.unsplash.com/photo-1501339847302-ac426a4a7cbb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1178&q=80', // 咖啡厅2
  'https://images.unsplash.com/photo-1566737236500-c8ac43014a67?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', // 夜店1
  'https://images.unsplash.com/photo-1578736641330-3155e606cd40?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', // 夜店2
];

// 根据商家类型获取默认图片
const getDefaultImageByType = (type) => {
  switch (type.toLowerCase()) {
    case 'bar':
      return DEFAULT_BUSINESS_IMAGES[0];
    case 'restaurant':
      return DEFAULT_BUSINESS_IMAGES[2];
    case 'cafe':
      return DEFAULT_BUSINESS_IMAGES[4];
    case 'club':
      return DEFAULT_BUSINESS_IMAGES[6];
    default:
      return DEFAULT_BUSINESS_IMAGES[Math.floor(Math.random() * DEFAULT_BUSINESS_IMAGES.length)];
  }
};

// 创建 axios 实例
const api = axios.create({
  baseURL: config.ES_ENDPOINT,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    // 如果需要认证，在这里添加认证头
    // 'Authorization': 'Basic ' + btoa('user:password')
  }
});

// 添加响应拦截器用于错误处理
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', error);
    if (error.code === 'ECONNREFUSED') {
      throw new Error('Unable to connect to Elasticsearch. Please ensure the service is running.');
    }
    if (error.response) {
      // 服务器返回了错误状态码
      throw new Error(error.response.data?.error?.reason || 'An error occurred while connecting to the server');
    }
    throw error;
  }
);

// 测试连接
const testConnection = async () => {
  try {
    const response = await api.get('/');
    console.log('Elasticsearch connection successful:', response.data);
    return true;
  } catch (error) {
    console.error('Elasticsearch connection failed:', error.message);
    return false;
  }
};

export const businessService = {
  testConnection,

  // 创建新商家
  async createBusiness(businessData) {
    try {
      // 首先测试连接
      const isConnected = await testConnection();
      if (!isConnected) {
        throw new Error('Cannot connect to Elasticsearch');
      }

      let imageUrl;
      if (businessData.storeImage) {
        // 如果上传了图片，使用上传的图片
        imageUrl = URL.createObjectURL(businessData.storeImage);
      } else {
        // 否则使用默认图片
        imageUrl = getDefaultImageByType(businessData.storeType);
      }

      const response = await api.post(`/${config.BUSINESS_INDEX}/_doc`, {
        name: businessData.storeName,
        type: businessData.storeType,
        phone: businessData.storePhone,
        address: businessData.storeAddress,
        business_hours: businessData.businessHours,
        image_url: imageUrl,
        applicant: {
          name: businessData.applicantName,
          email: businessData.applicantEmail
        },
        status: 'pending',
        created_at: new Date().toISOString(),
        rating: 0,
        review_count: 0
      });
      return response.data;
    } catch (error) {
      console.error('Error creating business:', error);
      throw error;
    }
  },

  // 获取所有商家
  async getAllBusinesses(page = 1, size = 10) {
    try {
      const response = await api.post(`/${config.BUSINESS_INDEX}/_search`, {
        from: (page - 1) * size,
        size: size,
        sort: [
          { rating: { order: "desc" } },
          { review_count: { order: "desc" } }
        ],
        query: {
          match_all: {}
        }
      });
      return {
        businesses: response.data.hits.hits.map(hit => ({
          id: hit._id,
          ...hit._source
        })),
        total: response.data.hits.total.value
      };
    } catch (error) {
      console.error('Error fetching businesses:', error);
      throw error;
    }
  },

  // 搜索商家
  async searchBusinesses(query, page = 1, size = 10) {
    try {
      const response = await api.post(`/${config.BUSINESS_INDEX}/_search`, {
        from: (page - 1) * size,
        size: size,
        query: {
          multi_match: {
            query: query,
            fields: ["name^3", "type^2", "address"],
            fuzziness: "AUTO"
          }
        }
      });
      return {
        businesses: response.data.hits.hits.map(hit => ({
          id: hit._id,
          ...hit._source
        })),
        total: response.data.hits.total.value
      };
    } catch (error) {
      console.error('Error searching businesses:', error);
      throw error;
    }
  },

  // 获取单个商家详情
  async getBusinessById(id) {
    try {
      const response = await api.get(`/${config.BUSINESS_INDEX}/_doc/${id}`);
      return {
        id: response.data._id,
        ...response.data._source
      };
    } catch (error) {
      console.error('Error fetching business:', error);
      throw error;
    }
  },

  // 更新商家信息
  async updateBusiness(id, updateData) {
    try {
      const response = await api.post(`/${config.BUSINESS_INDEX}/_update/${id}`, {
        doc: updateData
      });
      return response.data;
    } catch (error) {
      console.error('Error updating business:', error);
      throw error;
    }
  },

  // 添加评论
  async addReview(businessId, reviewData) {
    try {
      // 首先获取当前商家信息
      const business = await this.getBusinessById(businessId);
      
      // 计算新的评分
      const newRating = (business.rating * business.review_count + reviewData.rating) / (business.review_count + 1);
      
      // 更新商家信息
      await this.updateBusiness(businessId, {
        rating: Number(newRating.toFixed(1)),
        review_count: business.review_count + 1
      });

      // 创建评论
      const response = await api.post(`/${config.REVIEW_INDEX}/_doc`, {
        business_id: businessId,
        rating: reviewData.rating,
        content: reviewData.content,
        user_name: reviewData.userName,
        created_at: new Date().toISOString()
      });

      return response.data;
    } catch (error) {
      console.error('Error adding review:', error);
      throw error;
    }
  },

  // 获取商家评论
  async getBusinessReviews(businessId, page = 1, size = 10) {
    try {
      const response = await api.post(`/${config.REVIEW_INDEX}/_search`, {
        from: (page - 1) * size,
        size: size,
        sort: [
          { created_at: { order: "desc" } }
        ],
        query: {
          term: {
            business_id: businessId
          }
        }
      });
      return {
        reviews: response.data.hits.hits.map(hit => ({
          id: hit._id,
          ...hit._source
        })),
        total: response.data.hits.total.value
      };
    } catch (error) {
      console.error('Error fetching reviews:', error);
      throw error;
    }
  }
}; 